/**
 * Reflection Block Component
 *
 * Displays AI reflection/thinking content with streaming support and collapsible thinking blocks
 */

import { IconChevronRight } from "@intentui/icons";
import { MarkdownRenderer } from "@renderer/components/business/markdown/markdown-renderer";
import { Button } from "@renderer/components/ui/base/button";
import { useContentBlocks } from "@renderer/hooks/use-content-blocks";
import { cn } from "@renderer/lib/utils";
import type { ChatSettings } from "@shared/types/chat-settings";
import type { ReflectionContentBlock } from "@shared/types/sequential-content";
import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";

interface ReflectionBlockProps {
  block: ReflectionContentBlock;
  messageId?: string; // Optional for potential future use
  settings: ChatSettings;
  className?: string;
}

export function ReflectionBlock({
  block,
  settings,
  className = "",
}: ReflectionBlockProps) {
  const { t } = useTranslation("translation", {
    keyPrefix: "message",
  });
  const { hideReason, collapseThinkBlock, disableMarkdown } = settings;

  // Parse thinking process content using the same logic as ContentBlocks
  const { blocks: thinkingBlocks, cleanContent } = useContentBlocks(
    block.content,
  );

  const [collapsedStates, setCollapsedStates] = useState<
    Record<string, boolean>
  >(() => {
    if (!collapseThinkBlock) return {};
    // Set collapsed state for complete thinking blocks
    const initialStates: Record<string, boolean> = {};
    thinkingBlocks.forEach((thinkBlock, index) => {
      const blockId = `${block.id}-${thinkBlock.type}-${index}`;
      if (thinkBlock.isComplete) {
        initialStates[blockId] = true;
      }
    });
    return initialStates;
  });

  const previousCompleteStates = useRef<Record<string, boolean>>({});

  useEffect(() => {
    if (hideReason) return;
    // Auto-collapse when thinking blocks complete
    thinkingBlocks.forEach((thinkBlock, index) => {
      const blockId = `${block.id}-${thinkBlock.type}-${index}`;
      const wasComplete = previousCompleteStates.current[blockId];
      const isNowComplete = thinkBlock.isComplete;

      if (!wasComplete && isNowComplete && collapseThinkBlock) {
        setCollapsedStates((prev) => ({
          ...prev,
          [blockId]: true,
        }));
      }

      previousCompleteStates.current[blockId] = isNowComplete;
    });
  }, [thinkingBlocks, block.id, collapseThinkBlock, hideReason]);

  const hasContent = block.content && block.content.trim().length > 0;

  // Don't render anything if there's no content
  if (!hasContent) {
    return null;
  }

  const toggleCollapse = (blockId: string) => {
    setCollapsedStates((prev) => ({
      ...prev,
      [blockId]: !prev[blockId],
    }));
  };

  // If hideReason is true, don't show thinking blocks
  if (hideReason) {
    return cleanContent ? (
      <div className={className}>
        <div className="prose prose-sm max-w-none">
          <MarkdownRenderer settings={settings}>
            {cleanContent}
          </MarkdownRenderer>
        </div>
      </div>
    ) : null;
  }

  return (
    <div className={className}>
      {/* Render thinking/reasoning blocks if present */}
      {thinkingBlocks.length > 0 && (
        <div className="mb-4">
          {thinkingBlocks.map((thinkBlock, index) => {
            const blockId = `${block.id}-${thinkBlock.type}-${index}`;
            const isCollapsed = collapsedStates[blockId] ?? false;

            return (
              <div
                key={blockId}
                className={cn(
                  "my-3 rounded-lg border border-muted-fg/30 border-dashed bg-muted/30 px-4 py-2",
                  "hover:border-muted-fg/50",
                )}
              >
                <Button
                  intent="plain"
                  size="sm"
                  onPress={() => toggleCollapse(blockId)}
                  className="flex h-8 w-full cursor-pointer items-center gap-2 pressed:bg-transparent text-fg text-sm hover:bg-transparent"
                >
                  <div className="flex w-full items-center gap-2">
                    <motion.div
                      animate={{ rotate: isCollapsed ? 90 : -90 }}
                      transition={{ duration: 0.3, ease: "easeInOut" }}
                    >
                      <IconChevronRight className="size-5" />
                    </motion.div>
                    {thinkBlock.type === "think" ? t("think") : t("reason")}

                    <span className="ml-1 text-xs">
                      (
                      {!thinkBlock.isComplete ? t("outputing") : t("completed")}
                      )
                    </span>
                  </div>
                </Button>

                <AnimatePresence initial={false}>
                  {!isCollapsed && (
                    <motion.div
                      initial={{ height: 0 }}
                      animate={{ height: "auto" }}
                      exit={{ height: 0 }}
                      transition={{
                        height: { duration: 0.3, ease: "easeInOut" },
                      }}
                      className="overflow-hidden"
                    >
                      <div className="text-muted-fg text-sm leading-relaxed">
                        {disableMarkdown ? (
                          <div className="whitespace-pre-wrap">
                            {thinkBlock.content}
                          </div>
                        ) : (
                          <MarkdownRenderer settings={settings}>
                            {thinkBlock.content}
                          </MarkdownRenderer>
                        )}
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>
            );
          })}
        </div>
      )}

      {/* Render regular content if present */}
      {cleanContent && (
        <div className="prose prose-sm max-w-none">
          <MarkdownRenderer settings={settings}>
            {cleanContent}
          </MarkdownRenderer>
        </div>
      )}
    </div>
  );
}
